package com.tao.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.opensymphony.xwork2.interceptor.annotations.Allowed;
import com.tao.action.BaseAction;
import com.tao.domain.Group;
import com.tao.domain.PolMenu;
import com.tao.domain.User;
import com.tao.service.group.GroupService;
import com.tao.service.menu.SubMenuService;
import com.tao.service.user.UserService;
import com.tao.util.ThreadLostener;
import com.tao.util.Utils;
import com.tao.util.pack.BaseResponeBean;
import com.tao.util.pack.BaseResponeBean.UserEntity;
import com.tao.util.pack.HeartBeatThread.OnExitMsgListener;
import com.tao.util.pack.HeartBeatThread.OnNewMsgListener;
import com.tao.util.pack.HeartBeatThread.OnStatsMsgListener;
import com.tao.util.pack.HeartSendThread;
import com.tao.util.pack.HeartSendThread.OnExitSendMsgListener;
import com.tao.util.pack.HeartSendThread.OnSendMsgListener;
import com.tao.util.pack.WaitScanAndLoginThread.OnScanListener;
import com.tao.util.pack.WeChatClass.OnContentListener;
import com.tao.util.pack.WeChatClass.OnInitMsgListener;
import com.tao.util.pack.WeChatClass;

@SuppressWarnings("serial")
public class UserAction extends BaseAction implements SessionAware,
		RequestAware {

	/************** 定义变量及参数 ******************************/

	@SuppressWarnings("rawtypes")
	@Allowed
	Map session;
	private User user;
	@SuppressWarnings("rawtypes")
	@Allowed
	Map request;
	private String result;
	PolMenu polMenu;
	@Allowed
	UserService userService;
	@Allowed
	GroupService groupService;
	@Autowired
	private SubMenuService subMenuService; // 分局
	
	
	/******************* end ****************************/

	@Override
	public String execute() throws Exception {
		
		
		return SUCCESS;
	}
	public String getViewLogin() {
		return INPUT;
	}
	@SuppressWarnings("unchecked")
	public void getHttpUserList() {
		session.remove("result");
		
		session.put("pol_id", polMenu.getPol_id());
		session.remove("json");
		// 实例化主线程
		final WeChatClass weChat = new WeChatClass();
		
		//登录微信号主线程监听
		LoginMsgWeChatClassMsg(weChat);
		//主线程中微信群新消息程监听
		NewMsgWeChatClassMsg(weChat);
		//主线程中微信心跳状态监控监听
		HeartStatsMsgWeChatClassMsg(weChat);
		//主线程中微信号退出线程监听
		ExitWeChatClassMsg(weChat);
		//获取主线程初始化返回的微信号数据并添加到数据库
		getContentInitUser(weChat);
		//获取主线程返回的群号数据并添加到数据库
		getContentGroup(weChat);
		//启动主线程登录返回二维码信息到前台
		String uuid = weChat.gogogo();
		
		request.put("uuid", uuid);
		getResult(uuid);

	}

	/**
	 * 登录微信号主线程监听
	 * 
	 * @param weChat
	 */
	public void LoginMsgWeChatClassMsg(WeChatClass weChat) {
		
		
		session.put("result", "");
		weChat.setmScanListener(new OnScanListener() {

			@Override
			public void onSure() {
				System.out.println("登陆成功");
				result = "登陆成功:"+Utils.getSystemTime();
				session.put("result", result);
				session.put("mark", "1");
				
			}

			@Override
			public void onScan() {
				System.out.println("已经扫描成功，等待确认登陆");
				result = "已经扫描成功，等待确认登陆:"+Utils.getSystemTime();
				session.put("result", result);
				session.put("mark", "1");
				
			}
		});

	}

	/**
	 * 主线程中微信群新消息程监听
	 * 
	 * @param weChat
	 */
	public void NewMsgWeChatClassMsg(WeChatClass weChat) {

		weChat.setmNewMsgListener(new OnNewMsgListener() {

			@Override
			public void onNewMsg(String text) {// 只处理群消息
				System.out.println("接收到消息:" + text);
				result = "接收到消息:" + text;

			}

			@Override
			public void startBeat(String uin) {
				System.out.println("开始心跳");
				result = "开始心跳:"+Utils.getSystemTime();
				if(null!=session.get("mark")){
					session.put("result", "开始心跳");
				}else{
					session.put("result", "轮询心跳");
				}
			}
		});
	}
	/**
	 * 主线程中微信心跳状态监控监听
	 * 
	 * @param weChat
	 */
	public void HeartStatsMsgWeChatClassMsg(WeChatClass weChat) {

		weChat.setmStatsMsgListener(new OnStatsMsgListener() {
			
			@Override
			public void onStatsMsg(String text) {
				result = text;
				session.put("result", result);
			}
		});
	}

	/**
	 * 主线程中微信号退出线程监听
	 * 
	 * @param weChat
	 */
	public void ExitWeChatClassMsg(WeChatClass weChat) {

		weChat.setmExitMsgListener(new OnExitMsgListener() {

			@Override
			public void onExitMsg(String text) {
				result = text;
				System.out.println(text);
				result = text;
				
				session.put("result",result);
				session.remove("uuid");

			}
		});

	}

	/**
	 * 获取主线程初始化返回的微信号数据并添加到数据库
	 * 
	 * @param weChat
	 */
	public void getContentInitUser(WeChatClass weChat) {

		weChat.setmInitMsgListener(new OnInitMsgListener() {

			@Override
			public void onInitMsg(String text, String[] s) {

				result = text;
				BaseResponeBean brespon = new Gson().fromJson(text,
						BaseResponeBean.class);
				User user = new User();
				user.setUin(brespon.getUser().getUin());
				
				userService.delete(user);
				
				user.setNickName(brespon.getUser().getNickName());
				user.setUserName(brespon.getUser().getUserName());
				user.setHeadImgUrl(brespon.getUser().getHeadImgUrl());
				user.setPol_id((String)session.get("pol_id"));
				session.remove("pol_id");
				user.setSkey(s[1]);
				user.setSid(s[0]);
				user.setPass_ticket(s[2]);
				user.setCookie(s[3]);
				user.setLoginTime(Utils.getSystemTime());
				userService.insert(user);
				
				// 启动维持账号生命线程
				startHeartSendThread(user);

				// java.util.List<UserEntity> list = brespon.getContactList();
				// for(UserEntity uEntity:list){
				// if(uEntity.getUserName().startsWith("@@")){
				// Group group = new Group();
				// group.setUin(brespon.getUser().getUin());
				// group.setGroupName(uEntity.getUserName());
				// group.setGroupNickName(uEntity.getNickName());
				// group.setHeadImgUrl(uEntity.getHeadImgUrl());
				// groupService.insert(group);
				// }
				// }

			}
		});
		//
	}

	/**
	 * 获取主线程返回的群号数据并添加到数据库
	 * 
	 * @param weChat
	 */
	public void getContentGroup(WeChatClass weChat) {

		weChat.setmContentListener(new OnContentListener() {

			@Override
			public void onContentMsg(String text, String uin) {
				result = text;
				BaseResponeBean brespon = new Gson().fromJson(text,
						BaseResponeBean.class);
				java.util.List<UserEntity> list = brespon.getMemberList();

				System.out.println("群号存入数据库---------------------" + uin);
				Group gr = new Group();
				gr.setUin(uin);
				groupService.delete(gr);
				for (UserEntity uEntity : list) {
					if (uEntity.getUserName().startsWith("@@")) {
						Group group = new Group();
						group.setUin(uin);
						group.setGroupName(uEntity.getUserName());
						group.setGroupNickName(uEntity.getNickName());
						group.setHeadImgUrl(uEntity.getHeadImgUrl());
						groupService.insert(group);
					}
				}

			}
		});

	}

	/**
	 * 维持账号生命周期线程
	 */
	public void startHeartSendThread(User user) {

		// 开启维持账号生命周期线程
		HeartSendThread hThread = new HeartSendThread(user);
		//
		hThread.setmSendMsgListener(new OnSendMsgListener() {

			@Override
			public void startBeat() {
				System.out.println("开启维持账号生命周期线程");
				result = "开启维持账号生命周期线程:"+Utils.getSystemTime();
				
					session.put("result",result);
				
			}

			@Override
			public void onNewMsg(String text) {
				session.put("result",result);

			}
		});
		// 退出监听
		hThread.setmExitSendMsgListener(new OnExitSendMsgListener() {

			@Override
			public void onExitMsg(String text) {
				System.out.println(text + ":维持账号生命周期线程关闭");

			}
		});
		
		//设置线程名称
		hThread.setName(hThread.getUser().getSid());
		//添加到线程监控的map
		ThreadLostener.heartSendThreadMap.put(hThread.getName(), hThread);
		
		hThread.start();

	}
	public void getResult(String data){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
			try {
					response.getWriter().print(data);
					
			} catch (IOException e) {
			}
	}
	public void getResults(){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
			try {
					response.getWriter().print(session.get("result"));
					
			} catch (IOException e) {
			}
	}
	/******************** 实体映射 **************************/

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@SuppressWarnings("rawtypes")
	public Map getSession() {
		return session;
	}

	@SuppressWarnings("rawtypes")
	public void setSession(Map session) {
		this.session = session;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public GroupService getGroupService() {
		return groupService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	@SuppressWarnings("rawtypes")
	public Map getRequest() {
		return request;
	}

	@SuppressWarnings("rawtypes")
	public void setRequest(Map request) {
		this.request = request;
	}
	
	public void wxLoginchick(){
		//System.out.println("ajax轮询====================="+session.get("result"));
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;chareset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			out.print(session.get("result"));
			out.flush();
			out.close();
		}
	}
	
	public String wxLoginjun(){
		session.remove("mark");
		return SUCCESS;
	}
	
	/**
	 * 刷新登录二维码图片
	 */
	public void getReUuid(){
		session.remove("result");
		// 实例化主线程
		final WeChatClass weChat = new WeChatClass();
		
		//登录微信号主线程监听
		LoginMsgWeChatClassMsg(weChat);
		//主线程中微信群新消息程监听
		NewMsgWeChatClassMsg(weChat);
		//主线程中微信心跳状态监控监听
		HeartStatsMsgWeChatClassMsg(weChat);
		//主线程中微信号退出线程监听
		ExitWeChatClassMsg(weChat);
		//获取主线程初始化返回的微信号数据并添加到数据库
		getContentInitUser(weChat);
		//获取主线程返回的群号数据并添加到数据库
		getContentGroup(weChat);
		//启动主线程登录返回二维码信息到前台
		String uuid = weChat.gogogo();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;chareset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			out.print(uuid);
			out.flush();
			out.close();
		}
	}
	
	/**
	 * 获取维持生命的线程
	 */
	public void getThread(){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;chareset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			out.print(ThreadLostener.getThreadNameList());
			out.flush();
			out.close();
		}
	
	}
	

	/**
	 * 生命的线程页面
	 */
	public String Thread(){
		return "thread";
		
	}
	
	String threadName;
	
	public String getThreadName() {
		return threadName;
	}

	public void setThreadName(String threadName) {
		this.threadName = threadName;
	}

	/**
	 * 关闭线程
	 */
	public void closeThread() {
		if(null!=threadName){
			ThreadLostener.closeThread(threadName);	
		}
	}
	
	public void closeBeatThread() {
		if(null!=threadName){
			ThreadLostener.closeBeatThread(threadName);	
		}
	}
	
	public void reopen() {
		if(null!=threadName){
			ThreadLostener.reopen(threadName);	
		}
	}
	
	public void reBeat() {
		if(null!=threadName){
			ThreadLostener.reBeat(threadName);	
		}
	}

	public PolMenu getPolMenu() {
		return polMenu;
	}

	public void setPolMenu(PolMenu polMenu) {
		this.polMenu = polMenu;
	}
	public SubMenuService getSubMenuService() {
		return subMenuService;
	}
	public void setSubMenuService(SubMenuService subMenuService) {
		this.subMenuService = subMenuService;
	}

}
